package cn.com.freelibra.forum.job;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;

import cn.com.freelibra.forum.po.JobMessage;
import cn.com.freelibra.forum.po.JobSetting;
import cn.com.freelibra.forum.service.JobMessageService;
import cn.com.freelibra.forum.service.JobSettingService;
import cn.com.freelibra.forum.util.StringUtil;
import cn.com.freelibra.forum.util.constentEnum.OriginEnum;

@DisallowConcurrentExecution
public class JobMessagQuartzJob implements Job {

	private static final String APPLICATION_CONTEXT_KEY = "applicationContext";

	public static ApplicationContext getApplicationContext(JobExecutionContext context) throws Exception {
		ApplicationContext appCtx = null;
		appCtx = (ApplicationContext) context.getScheduler().getContext().get(APPLICATION_CONTEXT_KEY);
		if (appCtx == null) {
			throw new JobExecutionException("No application context available in scheduler context for key \""
					+ APPLICATION_CONTEXT_KEY + "\"");
		}
		return appCtx;
	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		ApplicationContext applicationContext = null;
		try {
			applicationContext = JobMessagQuartzJob.getApplicationContext(context);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("任务成功运行");
		JobSetting scheduleJob = (JobSetting) context.getMergedJobDataMap().get("JobSetting");
		JobMessageService jobMessageService = (JobMessageService) applicationContext.getBean("jobMessageService");
		doJob(jobMessageService);

		System.out.println("任务名称 = [" + scheduleJob.getJobName() + "]");
		// 定时任务执行完成需要更新数据库
		JobSettingService jobSettingService = (JobSettingService) applicationContext.getBean("jobSettingService");
		scheduleJob.setExecuteTime(new Date());
		jobSettingService.updateJobSetting(scheduleJob);

	}

	public String doJob(JobMessageService jobMessageService) {
		Pattern pattern = Pattern
				.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
		boolean hasNextPage = true;
		Document doc = null;
		String model="http://sou.zhaopin.com/jobs/searchresult.ashx?jl=深圳&kw=java&p=";
		int i=1;
		String nextPageUrl = model+i;
		int flagTimeOut = 0;
		while (hasNextPage) {
			System.out.println(nextPageUrl);
			try {
				doc = Jsoup.connect(nextPageUrl).get();
			} catch (IOException e1) {
			}
			Element content = doc.getElementById("newlist_list_content_table");
			Elements zwmcEls = content.getElementsByClass("zwmc");
			List<JobMessage> jobMessageList = new ArrayList<JobMessage>();
			for (int j = 0; j < zwmcEls.size(); j++) {
				String contUrl = zwmcEls.get(j).select("a").attr("href").toString();
				// 判断是否为网页 如果不是不进行抓取
				if (pattern.matcher(contUrl).matches() && contUrl.length() == 43) {
					JobMessage jobMessage = new JobMessage();
					Document contentHtml = null;
					try {
						contentHtml = Jsoup.connect(contUrl).get();
					} catch (IOException e) {
						flagTimeOut++;
						if(flagTimeOut>2){
							System.out.println("已经丢失链接!!!!!!!!!!!!!!!!!!!!");
						}
					}
					// 头部信息
					Elements detailUL = contentHtml.select(".fixed-inner-box");
					String category = detailUL.select("h1").text();
					jobMessage.setPosition(category);
					// 公司名称
					String companyName = detailUL.select("h2").text();
					jobMessage.setCompanyName(companyName);

					// 职位描述详细信息
					Elements contentUL = contentHtml.select(".terminalpage-left > ul > li");
					if (contentUL.size() > 0) {
						// 薪水
						jobMessage.setSalary(contentUL.get(0).select("strong").text());
						jobMessage.setCity(contentUL.get(1).select("strong").text());
						// 发布日期
						jobMessage.setReleaseDate(contentUL.get(2).select("strong").text());
						jobMessage.setWorkingProperty(contentUL.get(3).select("strong").text());
						jobMessage.setWorkExp(contentUL.get(4).select("strong").text());
						jobMessage.setEducation(contentUL.get(5).select("strong").text());
						jobMessage.setRecruitment(contentUL.get(6).select("strong").text());
						jobMessage.setCategory(contentUL.get(7).select("strong").text());
						// Elements remarker =
						// contentHtml.select(".tab-inner-cont");
						// jobMessage.setJobDescribe(remarker.get(0).text());
						// jobMessage.setCompanyDescription(remarker.get(1).text());
						jobMessage.setOrigin(OriginEnum.zhilian.getOrigin());
						// jobMessageService.saveJobMessage(jobMessage);
						jobMessageList.add(jobMessage);
					}
				} else {
//					System.out.println("这不是一个正常的社招网址:" + contUrl);
				}
			}
			i++;
			jobMessageService.savebatchJobMessage(jobMessageList);
			String flag = doc.select(".next-page").get(0).attr("href").toString();
			if (StringUtil.isEmpty(flag)) {
				System.out.println("显示完成:"+i);
				hasNextPage = false;
			}else{
				nextPageUrl = model+i;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "yes";
	}
}
